﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System;

public class ForcesDeployScene : Scene
{
    static MemberModel InitMember = null;

    static public void ModelForInitWithItemRoot(MemberModel model)
    {
        InitMember = model;
    }

    enum SCENEMODE
    {
        info,
    }

    public MemberModel m_SelectMember = null;

    SCENEMODE m_SceneMode = SCENEMODE.info;


    #region Left List 관련 변수
    int m_MembersMax = 0;
    List<int> m_MembersNo = new List<int>();

    public Animation m_LeftListAni;
    public GameObject m_LeftListOrizin;
    const float ListMemberStartY = 135.0f;
    const float ListMemberGap = 195.0f;
    public List<Oc_MemberListItem> m_LeftListItems = new List<Oc_MemberListItem>();
    #endregion

	#region 아이템 관련 변수
	public GameObject m_MemberListRoot;
	
	#endregion

    #region 애니메이션 변수
    public Animation m_SortAni;
	public Animation m_FormationAni;

    #endregion


    #region 길드원 정렬 관련 변수
	public UILabel[] m_SortKindsLabel;
	bool m_IsSortMenuOn = false;
	SortKind m_SortKind = SortKind.Level;
	string tempString0 = null;
	string tempString1 = null;
	string tempString2 = null;
    #endregion

	public UILabel[] m_FormationKindsLabel;
	public GameObject[] m_FormationButton;
	bool m_IsFormationMenuOn = false;
	string tempFormation1String = null;
	string tempFormation2String = null;
	string tempFormation3String = null;

    #region leftlist 무빙 관련
    public UIScrollView m_LeftScrollView;
    const float LeftListScrollViewStartPositonY = -128.0f;
    const float LeftListScrollViewStartOffSetY = -300.0f;
    public bool m_IsLeftListMoving = false;

    public Animation m_LeftBottomAni;
   
	#region 임시 ui버튼 관련
	public GameObject delButton;
	#endregion
	public bool isModifyMode; // 수정 모드 인가//
	public GameObject viewingModePanel;
	public GameObject modifyModePanel;
	public int nCurFormation = 1;
	public GameObject [] formationPopupGo;
	float srollViewMinY = -128;
	float srollViewMaxY = 4708;
	float leftListMiddleY;
	float leftListMinY;
	float leftListMaxY;
	Transform selectedMemberListItemTrans;
	bool bShouldListMoveUp;
	bool bShouldListMoveDown;
	public float [] autoScrollSpeed;
	int nAutoScrollSpeedIndex;
	Vector3 autoScrollTranslate;

    void UpdateLeftScrollView()
    {
        if(m_IsLeftListMoving)
        {
            SpringPanel sp = m_LeftScrollView.GetComponent("SpringPanel") as SpringPanel;
            if (sp != null)
                sp.enabled = false;

            UIPanel up = m_LeftScrollView.GetComponent("UIPanel") as UIPanel;
            Vector2 offSet = up.clipOffset;
            offSet.y = LeftListScrollViewStartOffSetY - m_LeftScrollView.transform.localPosition.y + LeftListScrollViewStartPositonY;
            up.clipOffset = offSet;
        }

		if(bShouldListMoveDown) {
			//LeanTween.moveLocalY( m_LeftScrollView.gameObject, srollViewMaxY, 1.0f).setEase(LeanTweenType.easeOutSine);
			autoScrollTranslate.y = -autoScrollSpeed[nAutoScrollSpeedIndex] * Time.deltaTime;
			m_LeftScrollView.MoveRelative( autoScrollTranslate );
			//if(m_LeftScrollView.transform.localPosition.y > srollViewMaxY)
			//	bShouldListMoveDown=false;
			if(selectedMemberListItemTrans.position.y>=leftListMinY && selectedMemberListItemTrans.position.y<=leftListMaxY)
				bShouldListMoveDown=false;
		}
		if(bShouldListMoveUp) {
			autoScrollTranslate.y = autoScrollSpeed[nAutoScrollSpeedIndex] * Time.deltaTime;
			m_LeftScrollView.MoveRelative( autoScrollTranslate );
			//if(m_LeftScrollView.transform.localPosition.y < leftListMinY)
			//	bShouldListMoveUp=false;
			if(selectedMemberListItemTrans.position.y>=leftListMinY && selectedMemberListItemTrans.position.y<=leftListMaxY)
				bShouldListMoveUp=false;
		}

    }
    #endregion


    //public GameObject m_TraitIncEffect;

    public Transform m_LightProbeAnchorRoot;

    void SetSortMenuUI(int num)        // 소트 메뉴 라벨 설정
    {
        m_SortKind = (SortKind)(((int)m_SortKind + num) % 3);   // 각 상황마다 대응

        switch (m_SortKind)
        {
            case SortKind.Level:
                m_SortKindsLabel[0].text = tempString0;
                m_SortKindsLabel[1].text = tempString1;
                m_SortKindsLabel[2].text = tempString2;
                break;
            case SortKind.Rare:
                m_SortKindsLabel[0].text = tempString1;
                m_SortKindsLabel[1].text = tempString2;
                m_SortKindsLabel[2].text = tempString0;
                break;
            case SortKind.Inhance:
                m_SortKindsLabel[0].text = tempString2;
                m_SortKindsLabel[1].text = tempString0;
                m_SortKindsLabel[2].text = tempString1;
                break;
        }

		SortLeftListMember();
        SetLeftListUI();

        if (m_SelectMember == null)
        {
            m_SelectMember = m_LeftListItems[0].m_MemberModel;
        }

        for (int i = 0; i < m_LeftListItems.Count; i++)
        {
            if (m_SelectMember.no == m_LeftListItems[i].m_MemberModel.no)
                m_LeftListItems[i].SetOn(false);
            else
                m_LeftListItems[i].SetOff();
        }
    }

	void SetFormationMenuUI(int num)
	{
		Debug.Log("formation change  "+num);
		nCurFormation = num;
		switch (nCurFormation)
		{
		case 1:
			m_FormationButton[0].name = "Button_Formation_1";
			m_FormationKindsLabel[0].text = tempFormation1String;

			m_FormationButton[1].name = "Button_Formation_2";
			m_FormationKindsLabel[1].text = tempFormation2String;

			m_FormationButton[2].name = "Button_Formation_3";
			m_FormationKindsLabel[2].text = tempFormation3String;
			break;
		case 2:
			m_FormationButton[0].name = "Button_Formation_2";
			m_FormationKindsLabel[0].text = tempFormation2String;
			
			m_FormationButton[1].name = "Button_Formation_1";
			m_FormationKindsLabel[1].text = tempFormation1String;
			
			m_FormationButton[2].name = "Button_Formation_3";
			m_FormationKindsLabel[2].text = tempFormation3String;
			break;
		case 3:
			m_FormationButton[0].name = "Button_Formation_3";
			m_FormationKindsLabel[0].text = tempFormation3String;
			
			m_FormationButton[1].name = "Button_Formation_1";
			m_FormationKindsLabel[1].text = tempFormation1String;
			
			m_FormationButton[2].name = "Button_Formation_2";
			m_FormationKindsLabel[2].text = tempFormation2String;
			break;
		}
		ForcesDeploy.Instance.LoadDeploy(nCurFormation);
	}

	void SortLeftListMember()
	{
		m_MembersNo.Clear();
		
		List<Oc_MemberListItem> tList = new List<Oc_MemberListItem>();
		for(int i=0; i<m_LeftListItems.Count; i++)
			tList.Add ( m_LeftListItems[i]);

		int nMax = tList.Count;
		for (int i = 0; i < nMax - 1; i++)
		{
			for (int j = 0; j < nMax - 1; j++)
			{
				switch (m_SortKind)
				{
				case SortKind.Level:
				{
					if ( !ForcesDeploy.Instance.IsDeployed(tList[j].m_MemberModel.no) && ForcesDeploy.Instance.IsDeployed(tList[j + 1].m_MemberModel.no) )
					{
						Oc_MemberListItem t = tList[j];
						tList[j] = tList[j + 1];
						tList[j + 1] = t;
					}                                
				}
					break;
				case SortKind.Rare:
				{
					if (tList[j].m_MemberModel.rarity < tList[j + 1].m_MemberModel.rarity)
					{
						Oc_MemberListItem t = tList[j];
						tList[j] = tList[j + 1];
						tList[j + 1] = t;
					}   
				}
					break;
				case SortKind.Inhance:
				{
					if (tList[j].m_MemberModel.strengthening < tList[j + 1].m_MemberModel.strengthening)
					{
						Oc_MemberListItem t = tList[j];
						tList[j] = tList[j + 1];
						tList[j + 1] = t;
					}   
				}
					break;
				}
			}
		}
		
		for (int i = 0; i < nMax; i++)
		{
			m_MembersNo.Add(tList[i].m_MemberModel.no);
		}
	}

    void SortMember()
    {
        m_MembersNo.Clear();

        List<MemberModel> tList = new List<MemberModel>();

        if (m_SceneMode == SCENEMODE.info)
        {
            foreach (KeyValuePair<string, MemberModel> t in UserData.Instance.userModel.members_dic)
            {
                tList.Add(t.Value);
            }
        }

        int max = tList.Count;
        for (int i = 0; i < max - 1; i++)
        {
            for (int j = 0; j < max - 1; j++)
            {
                switch (m_SortKind)
                {
                    case SortKind.Level:
                        {
                            if (tList[j].level < tList[j + 1].level)
                            {
                                MemberModel t = tList[j];
                                tList[j] = tList[j + 1];
                                tList[j + 1] = t;
                            }                                
                        }
                        break;
                    case SortKind.Rare:
                        {
                            if (tList[j].rarity < tList[j + 1].rarity)
                            {
                                MemberModel t = tList[j];
                                tList[j] = tList[j + 1];
                                tList[j + 1] = t;
                            }   
                        }
                        break;
                    case SortKind.Inhance:
                        {
                            if (tList[j].strengthening < tList[j + 1].strengthening)
                            {
                                MemberModel t = tList[j];
                                tList[j] = tList[j + 1];
                                tList[j + 1] = t;
                            }   
                        }
                        break;
                }
            }
        }

        for (int i = 0; i < max; i++)
        {
            m_MembersNo.Add(tList[i].no);
        }
    }

    void OnLoginErrCallback(ResponseModel<UserModel> recvData)
    {
        Debug.LogError("OnLoginErrCallback");
    }

    void OnLoginCallback(ResponseModel<UserModel> userData)
    {
        UserData.Instance.userModel = userData.data;
        StartCoroutine("StartSceneWithDelay");
    }

    public override void AwakeScene()
    {        
        Instance = this;       
        
        //left리스트 드래그 스크롤뷰 설정
        UIDragScrollView tDs = m_LeftListOrizin.GetComponent("UIDragScrollView") as UIDragScrollView;
        tDs.scrollView = m_LeftScrollView;

	    Popup_Blur.ClearAll();

        // test version code  /////////////////////////////////////////////
        /**/
        if (UserData.Instance.userModel == null)
        {
            LoadingScene.TestInit();
            /**/
            NetworkManager.Instance.C2S_LOGIN(AuthPlatformID.None, BattleManager.Instance.battleTestId, string.Empty, OnLoginCallback, OnLoginErrCallback);
        }
        /////////////////////////////////////////////////////////////////
        else
        {
            StartCoroutine("StartSceneWithDelay");
        }
    }

    IEnumerator StartSceneWithDelay()
    {
        yield return new WaitForSeconds(0.1f);

		tempString0 = "배치";//TextController.GetStringWithId("uiCommonTextLevel");
        tempString1 = TextController.GetStringWithId("uiCommonTextRarityDo");
        tempString2 = TextController.GetStringWithId("uiCommonTextEnhance");

        //일단 레벨순으로 설정
        m_SortKindsLabel[0].text = tempString0;
        m_SortKindsLabel[1].text = tempString1;
        m_SortKindsLabel[2].text = tempString2;

		tempFormation1String = "진형1";
		tempFormation2String = "진형2";
		tempFormation3String = "진형3";
		m_FormationKindsLabel[0].text = tempFormation1String;
		m_FormationKindsLabel[1].text = tempFormation2String;
		m_FormationKindsLabel[2].text = tempFormation3String;

        m_MembersMax = UserData.Instance.userModel.members_dic.Count;      

        SortMember();
        CreateList();

		leftListMinY = m_LeftListItems[4].transform.position.y;
		leftListMiddleY = m_LeftListItems[2].transform.position.y;
		leftListMaxY = m_LeftListItems[0].transform.position.y;

        StartSceneAni();

		ForcesDeploy.Instance.LoadDeploy(nCurFormation);
		while(ForcesDeploy.isDeploying)
			yield return null;
		SortLeftListMember();
		SetLeftListUI();
    }

    void CreateList()
    {
        // 정렬메뉴 x -700 에서 씬 시작
        Vector3 pos = m_SortAni.transform.localPosition;
        pos.x = -700.0f;
        m_SortAni.transform.localPosition = pos;


        // 레프트 메뉴 x -700 에서 씬 시작
        GameObject temp = null;
        Oc_MemberListItem tempML = null;
        for (int i = 0; i < m_MembersMax; i++)
        {
            if (i > 0)
                temp = Instantiate(m_LeftListOrizin) as GameObject;
            else
                temp = m_LeftListOrizin;

            temp.transform.parent = m_LeftListOrizin.transform.parent;
            temp.transform.localScale = m_LeftListOrizin.transform.localScale;
            temp.name = string.Format("memberList_A{0}", i + 1);
            pos = m_LeftListOrizin.transform.localPosition;
            pos.x = -700.0f;
            pos.y = ListMemberStartY - (ListMemberGap * i);
            temp.transform.localPosition = pos;

            tempML = temp.GetComponent("Oc_MemberListItem") as Oc_MemberListItem;
            tempML.SetList(UserData.Instance.userModel.members_dic[m_MembersNo[i].ToString()]);
            m_LeftListItems.Add(tempML);
			SetDeployedCheck(temp, false);
        }


        if (m_SelectMember == null)
            m_SelectMember = m_LeftListItems[0].m_MemberModel;
        UpdateInfoUI();

        for (int i = 0; i < m_LeftListItems.Count; i++)
        {
            if (m_LeftListItems[i].m_MemberModel.no == m_SelectMember.no)
                m_LeftListItems[i].SetOn(false);
        }
    }

    void SetLeftListUI()
    {
        for (int i = 0; i < m_MembersMax; i++)
        {
            if (i < m_MembersNo.Count)
            {
                m_LeftListItems[i].gameObject.SetActive(true);
                m_LeftListItems[i].SetList(UserData.Instance.userModel.members_dic[m_MembersNo[i].ToString()]);
				SetDeployedCheck(m_LeftListItems[i].gameObject, ForcesDeploy.Instance.IsDeployed( m_LeftListItems[i].m_MemberModel.no) );
            }
            else
                m_LeftListItems[i].gameObject.SetActive(false);
        }
    }

    public override void StartScene()
    {
        //StartSceneAni();

        //Localization.language = "text_ko";
    }

    public void StartSceneAni()
    {

	    MemberListAni(true);
	}
   

    public void EndSceneAni()
    {
        m_LeftListAni.Play("info_detail_list OUT");
    }

	// 3d상에 배치된 캐릭터 클릭시//
	public void SetSelectMemberOnLeftUI(int no)
	{

		foreach (Oc_MemberListItem t_ML in m_LeftListItems)
		{
			if (t_ML.m_MemberModel.no== no) {
				m_SelectMember = t_ML.m_MemberModel;
				selectedMemberListItemTrans = t_ML.transform;
				t_ML.SetOn(true);
			}
			else
				t_ML.SetOff();
		}
		UpdateInfoUI();

		float delta = 0;
		if(selectedMemberListItemTrans.position.y<leftListMinY) {
			delta = leftListMinY-selectedMemberListItemTrans.position.y;
			bShouldListMoveUp = true;
			bShouldListMoveDown = false;
		}
		else if(selectedMemberListItemTrans.position.y>leftListMaxY) {
			delta = selectedMemberListItemTrans.position.y-leftListMaxY;
			bShouldListMoveUp = false;
			bShouldListMoveDown = true;
		}
		else {
			bShouldListMoveUp = false;
			bShouldListMoveDown = false;
		}

		Debug.Log("Delta  "+ delta);
		if(delta<=1)
			nAutoScrollSpeedIndex=0;
		else if(delta>1 && delta<2)
			nAutoScrollSpeedIndex=1;
		else if(delta>=2 && delta<3)
			nAutoScrollSpeedIndex=2;
		else
			nAutoScrollSpeedIndex=3;
	}

    public override void ButtonTouch(Collider collider)  // 버튼 터치 (터치 시작 끝 같은 오브젝트일때 터치 끝 시점에 호출)
    {
        Debug.Log(collider.name);

        if (collider.name.Contains("memberList_A"))
        {
			bShouldListMoveUp=false;
			bShouldListMoveDown=false;
            Oc_MemberListItem Choise_ML = collider.GetComponent("Oc_MemberListItem") as Oc_MemberListItem;

            if (m_SceneMode == SCENEMODE.info)
            {
                if (m_SelectMember.no != Choise_ML.m_MemberModel.no)      // 이전 선택 길드원과 다를때
                {
                    m_SelectMember = Choise_ML.m_MemberModel;
                    UpdateInfoUI();
                }
            }

            foreach (Oc_MemberListItem t_ML in m_LeftListItems)
            {
                if (t_ML.Equals(Choise_ML))
                    t_ML.SetOn(true);
                else
                    t_ML.SetOff();
            }
        }
        else if (collider.name.Contains("Button_Sort_"))
        {
            if (m_IsSortMenuOn)
            {
                string buttonName = collider.gameObject.name.Replace("Button_Sort_", "");
                int num = System.Convert.ToInt32(buttonName);
                SetSortMenuUI(num);
                m_SortAni.Play("sort_close");
            }
            else
            {
                m_SortAni.Play("sort_open");
            }
            m_IsSortMenuOn = !m_IsSortMenuOn;
        }
		else if (collider.name.Contains("Button_Formation_"))
		{
			if (m_IsFormationMenuOn)
			{
				string buttonName = collider.gameObject.name.Replace("Button_Formation_", "");
				int num = System.Convert.ToInt32(buttonName);
				SetFormationMenuUI(num);
				m_FormationAni.Play("sort_close");
				formationPopupGo[1].SetActive(false);
				formationPopupGo[2].SetActive(false);
			}
			else
			{
				m_FormationAni.Play("sort_open");
				for(int i=0; i<3; i++)
					formationPopupGo[i].SetActive(true);
			}
			m_IsFormationMenuOn = !m_IsFormationMenuOn;
			
		}
        else
        {
            switch (collider.gameObject.name)
            {
                case "Button_Sort":
                    if (m_IsSortMenuOn)
                        m_SortAni.Play("sort_close");
                    else
                        m_SortAni.Play("sort_open");

                    m_IsSortMenuOn = !m_IsSortMenuOn;
                    break;
				case "Button_Formation":
					if (m_IsFormationMenuOn) {
						m_FormationAni.Play("sort_close");
						formationPopupGo[1].SetActive(false);
						formationPopupGo[2].SetActive(false);
					}
                    else {
						m_FormationAni.Play("sort_open");
						for(int i=0; i<3; i++)
							formationPopupGo[i].SetActive(true);
					}

					m_IsFormationMenuOn = !m_IsFormationMenuOn;

                    break;
                case "Button_Infopopup":
                    PopupManager.PushPopup(PopupKind.Character_Info);
                    Debug.Log("Button_Infopopup");
                    break;

                case "Button_Back":
                    BackButton();
                    break;
            }
        }
    }

    void IgnoreTouch()
    {
        //isAbleControl = false;
        //StartCoroutine("UnignoreTouch");
    }

    IEnumerator UnignoreTouch()
    {
        yield return new WaitForSeconds(0.6f);
        IsAbleControl = true;
    }
    
    void EndLeftListMove()
    {
        m_IsLeftListMoving = false;
    }

    void LeftListCollidersOn()
    {
        for (int i = 0; i < m_LeftListItems.Count; i++)
        {
            m_LeftListItems[i].collider.enabled = true;
        }
    }

    public void MemberListAni(bool isIn)
    {
        m_IsLeftListMoving = true;

        iTween.MoveTo(m_LeftScrollView.gameObject, iTween.Hash("islocal", true, "y", LeftListScrollViewStartPositonY, "time", 0.2f, "easetype", "spring",
            "oncompletetarget", gameObject, "oncomplete", "EndLeftListMove"));

        if (isIn)
        {
            LeftListCollidersOn();

            Vector3 pos = m_SortAni.transform.localPosition;
            pos.x = -700.0f;
            m_SortAni.transform.localPosition = pos;

            iTween.MoveTo(m_SortAni.gameObject, iTween.Hash("islocal", true, "x", -3.0f, "time", 0.5f, "easetype", "spring"));

            int maxAni = System.Math.Min(m_LeftListItems.Count, 6);     // 한번에 보여줄수있는 최대 리스트 갯수 6개 이하 예외 처리
            for (int i = 0; i < maxAni; i++)
            {
                pos = m_LeftListItems[i].transform.localPosition;
                pos.x = -700.0f;
                m_LeftListItems[i].transform.localPosition = pos;

                iTween.MoveTo(m_LeftListItems[i].gameObject, iTween.Hash("islocal", true, "x", 1.0f, "time", 0.5f, "easetype", "spring", "delay", (i * 0.1f)));
            }

            for(int i = maxAni; i < m_LeftListItems.Count ; i++)
            {
                pos = m_LeftListItems[i].transform.localPosition;
                pos.x = 1.0f;
                m_LeftListItems[i].transform.localPosition = pos;
            }
        }
        else
        {
            for (int i = 0; i < m_LeftListItems.Count; i++)  // 아웃 무빙시 콜라이더 디스에이블
            {
                m_LeftListItems[i].collider.enabled = false;
            }

            Vector3 pos = m_SortAni.transform.localPosition;
            pos.x = -3.0f;
            m_SortAni.transform.localPosition = pos;

            iTween.MoveTo(m_SortAni.gameObject, iTween.Hash("islocal", true, "x", -700.0f, "time", 0.5f, "easetype", "spring"));      // 나가는 애니

            int maxAni = System.Math.Min(m_LeftListItems.Count, 6);     // 한번에 보여줄수있는 최대 리스트 갯수 6개 이하 예외 처리
            for (int i = 0; i < maxAni; i++)
            {
                pos = m_LeftListItems[i].transform.localPosition;
                pos.x = 1.0f;
                m_LeftListItems[i].transform.localPosition = pos;

                if(i == maxAni -1)  // 마지막 놈에 엔드 함수 호출
                    iTween.MoveTo(m_LeftListItems[i].gameObject, iTween.Hash("islocal", true, "x", -700.0f, "time", 0.5f, "easetype", "spring", "delay", (i * 0.1f))); // 나가는 애니                
                else
                    iTween.MoveTo(m_LeftListItems[i].gameObject, iTween.Hash("islocal", true, "x", -700.0f, "time", 0.5f, "easetype", "spring", "delay", (i * 0.1f))); // 나가는 애니
            }

            for (int i = maxAni; i < m_LeftListItems.Count; i++)
            {
                pos = m_LeftListItems[i].transform.localPosition;
                pos.x = -700.0f;
                m_LeftListItems[i].transform.localPosition = pos;
            }
        }
    }


    public override void BackButton()
    {
        if (m_SceneMode == SCENEMODE.info)
        {
            SceneController.LoadLevel("Main");
        }

    }

    public override void UpdateScene()
    {
        UpdateLeftScrollView();      
    }

    public override void HelpButton()
    {
        switch (m_SceneMode)
        {
            case SCENEMODE.info:
                {
                    Popup_Tutorial pt = PopupManager.PushPopup(PopupKind.Tutorial) as Popup_Tutorial;
                    pt.SetPopupWithTutorialKind(TutorialKind.helpCharInfoInfoA);
                    pt.SetEventOK(gameObject, "OnTutorialNext");
                }
                break;          
        }       
    }

    void OnTutorialNext()
    {
        Popup_Tutorial pt = PopupManager.PushPopup(PopupKind.Tutorial) as Popup_Tutorial;
        pt.SetPopupWithTutorialKind(TutorialKind.helpCharInfoInfoB);
    }

	#region 추가 기능 구현 함수들
	public void UpdateInfoUI()
	{
		ForcesDeploy.Instance.CheckDeployable(m_SelectMember, isModifyMode);
	}

	void SetDeployedCheck(GameObject go, bool bActivate)
	{
		go.transform.FindChild("Check").gameObject.SetActive(bActivate);
	}

	public MemberModel SetDeployedCheck(int no, bool bActivate)
	{
		for (int i = 0; i < m_LeftListItems.Count; i++)
		{
			if (m_LeftListItems[i].m_MemberModel.no == no) {
				SetDeployedCheck(m_LeftListItems[i].gameObject, bActivate);
				return m_LeftListItems[i].m_MemberModel;
			}
		}
		return null;
	}

	public void ClearDeployTagAll()
	{
		for(int i=0; i<m_LeftListItems.Count; i++)
			SetDeployedCheck(m_LeftListItems[i].gameObject, false);
	}

	public void SetDeployTag(int no)
	{
		for(int i=0; i<m_LeftListItems.Count; i++)
		{
			if(m_LeftListItems[i].m_MemberModel.no== no)
				SetDeployedCheck(m_LeftListItems[i].gameObject, true);
		}
	}

	#endregion

	#region 임시 기능 UI 버튼 클릭시 

	// 자동 배치 버튼
	void OnAutoClick()
	{
		if(ForcesDeploy.isDeploying) return;
		ForcesDeploy.isDeploying=true;
		ForcesDeploy.Instance.UnDeployAll();
		ClearDeployTagAll();
		StartCoroutine("CoAutoDeploy");
	}

	IEnumerator CoAutoDeploy()
	{
		List<Oc_MemberListItem> deployList = new List<Oc_MemberListItem>();
		List<Oc_MemberListItem> meleeChars = new List<Oc_MemberListItem>();
		List<Oc_MemberListItem> rangeChars = new List<Oc_MemberListItem>();

		for(int i=0; i<m_LeftListItems.Count; i++)
		{
			if( BattleFormula.IsMeleeAttack( m_LeftListItems[i].m_MemberModel.m_Stat.atkType ) )
				meleeChars.Add( m_LeftListItems[i]);
			else
				rangeChars.Add( m_LeftListItems[i]);
		}

		Debug.Log("melee="+meleeChars.Count+"  range="+rangeChars.Count);
		int nIndex = 0;
		while(meleeChars.Count< ForcesDeploy.Instance.lineMax[0])//밀리계열이 부족하면 레인지 계열로 채워넣는다
		{
			if(rangeChars.Count==0)
				break;
			nIndex = UnityEngine.Random.Range(0, rangeChars.Count);
			meleeChars.Add ( rangeChars[nIndex]);
			rangeChars.RemoveAt(nIndex);
		}
		
		while(deployList.Count< ForcesDeploy.Instance.lineMax[0])//밀리 계열 앞줄에 배치
		{
			if(meleeChars.Count==0)
				break;
			nIndex = UnityEngine.Random.Range(0, meleeChars.Count);
			deployList.Add ( meleeChars[nIndex]);
			meleeChars.RemoveAt(nIndex);
		}

		foreach(Oc_MemberListItem uiChar in meleeChars) // 남은 밀리계열은 레인지로 통합
			rangeChars.Add (uiChar);

		while(deployList.Count< ForcesDeploy.Instance.maxDeployable)//레인지 계열 나머지 배치
		{
			if(rangeChars.Count==0)
				break;
			nIndex = UnityEngine.Random.Range(0, rangeChars.Count);
			deployList.Add ( rangeChars[nIndex]);
			rangeChars.RemoveAt(nIndex);
		}
		nIndex=0;
		foreach(Oc_MemberListItem uiChar in deployList) {
			SetDeployedCheck(uiChar.gameObject, true);
			ForcesDeploy.Instance.Deploy(uiChar.m_MemberModel.no, uiChar.m_MemberModel.model, nIndex);
			nIndex++;
			yield return null;
		}
		ForcesDeploy.isDeploying=false;
		UpdateInfoUI();
	}

	void OnClearClick()
	{
		ForcesDeploy.Instance.UnDeployAll();
		ClearDeployTagAll();
	}

	//제외 버튼
	void OnDelClick()
	{
		if(ForcesDeploy.isDeploying) return;
		ForcesDeploy.Instance.UnDeploySelectedMember();
	}

	//수정 완료 버튼
	void OnModifyDoneClick()
	{
		isModifyMode=false;
		ForcesDeploy.Instance.SaveDeploy(nCurFormation);
		viewingModePanel.SetActive(true);
		modifyModePanel.SetActive(false);
		ForcesDeploy.Instance.TurnOffAllSpotFX();
	}

	//수정 취소 버튼
	void OnModifyCancelClick()
	{
		isModifyMode=false;
		viewingModePanel.SetActive(true);
		modifyModePanel.SetActive(false);
		ForcesDeploy.Instance.LoadDeploy(nCurFormation);
	}

	// 진형 수정 버튼
	void OnModifyStartClick()
	{
		isModifyMode=true;
		ForcesDeploy.Instance.CheckDeployable(m_SelectMember, isModifyMode);
		viewingModePanel.SetActive(false);
		modifyModePanel.SetActive(true);
	}
	#endregion
}
